<template>
  <div class="app-container">
    <el-card class="card-form">
      <div class="organization-title">项目明细报表</div>
      <el-form :model="queryForm" ref="queryForm" :inline="true">
        <el-form-item label="项目名称" prop="proName">
          <el-input
            v-model="queryForm.proName"
            placeholder="请输入"
            clearable
            size="small"
            style="width: 252px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="项目性质">
          <el-select v-model="queryForm.proNature" placeholder="请选择项目性质" clearable size="small" style="width: 252px">
            <el-option label="项目申报" value="0" />
            <el-option label="增手工录入" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="项目单位" prop="proCompany">
          <el-select
            v-model="queryForm.proCompany"
            placeholder="请选择"
            clearable
            size="small"
            style="width: 252px"
          >
            <el-option
              v-for="(item, index) in proCompanyOptions"
              :key="index"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目类别" prop="proType">
          <el-select v-model="queryForm.proType" placeholder="请选择项目类别" clearable size="small" style="width: 252px"> 
            <el-option label="建设类（新开工）" value="0" />
            <el-option label="建设类（续建）" value="1" />
            <el-option label="购买服务类" value="2" />
            <el-option label="运维类" value="3" />
            <el-option label="其他" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="投资估算（万元）">
          <el-input
            v-model="queryForm.proStartInvestmentEstimation"
            placeholder="请输入"
            clearable
            size="small"
            style="width: 120px"
            @input="
              queryForm.proStartInvestmentEstimation = queryForm.proStartInvestmentEstimation
                .replace(/[^\d^\.]+/g, '')
                .replace('.', '$#$')
                .replace(/\./g, '')
                .replace('$#$', '.')
            "
          />
          <span> - </span>
          <el-input
            v-model="queryForm.proEndInvestmentEstimation"
            placeholder="请输入"
            clearable
            size="small"
            style="width: 120px"
            @input="
              queryForm.proEndInvestmentEstimation = queryForm.proEndInvestmentEstimation
                .replace(/[^\d^\.]+/g, '')
                .replace('.', '$#$')
                .replace(/\./g, '')
                .replace('$#$', '.')
            "
          />
        </el-form-item>
        <el-form-item label="项目阶段" prop="proStag">
          <el-select
            v-model="queryForm.proStag"
            placeholder="请选择"
            clearable
            size="small"
            style="width: 252px"
          >
            <el-option label="项目申报" value="项目申报" />
            <el-option label="方案申报" value="方案申报" />
            <el-option label="项目实施" value="项目实施" />
            <el-option label="项目验收" value="项目验收" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="handleQuery"
            >查询</el-button
          >
          <el-button size="small" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="card-table">
      <el-row :gutter="10" class="mb20 mt5">
        <el-col :span="1.5"
          ><div style="fontsize: 14px; height: 32px; lineHeight: 32px">
            已勾选<span style="color: #3171ee; padding: 0 5px">{{
              lengthTotal
            }}</span
            >个项目
          </div>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" size="small" @click="exportClick" v-hasPermi="['project:details:exportSelect']"
            >导出勾选</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" size="small" @click="handleExport" v-hasPermi="['project:details:exportAll']"
            >导出全部</el-button
          >
        </el-col>
      </el-row>
      <el-table
        ref="multipleTable"
        v-loading="loading"
        :data="projectDetailsExportList"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column type="selection" align="center" width="65" />
        <el-table-column label="序号" align="center" width="65" type="index" />
        <el-table-column label="项目名称" align="center" prop="proName" :show-overflow-tooltip="true"/>
        <el-table-column label="项目性质" align="center" prop="proNature" :show-overflow-tooltip="true"/>
        <el-table-column label="项目类别" align="center" prop="proType" :show-overflow-tooltip="true"/>
        <el-table-column label="项目投资估算(万元)" align="center" prop="proInvestmentEstimation" :show-overflow-tooltip="true"/>
        <el-table-column label="项目阶段" align="center" prop="proStag" :show-overflow-tooltip="true"/>
        <el-table-column label="项目节点" align="center" prop="proNode" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="项目申报时间" align="center" prop="proTime" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="项目建设单位" align="center" prop="proCompany" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="项目所属部门" align="center" prop="proDept" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="项目联系人" align="center" prop="proRelationUser" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="项目联系人电话" align="center" prop="proRelationUserPhone" :show-overflow-tooltip="true"></el-table-column>
        <!-- <el-table-column label="资料库" align="center" prop="fileName" :show-overflow-tooltip="true"></el-table-column> -->
        <el-table-column
          label="资料库"
          align="center"
          class-name="small-padding fixed-width"
          width="160"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <div v-if="scope.row.fileName">
              <el-button size="medium" type="text" class="file-btn-width" @click="$download(scope.row.fileUrl)">{{scope.row.fileName}}</el-button>
              <i class="el-icon-circle-close" @click="handDelFile(scope.row)"></i>
            </div>
            <el-upload
              v-if="!scope.row.fileName"
              :ref="`uploadFileRow${scope.$index}`"
              :action="upload.url"
              :headers="upload.headers"
              :limit="1"
              :on-progress="handleFileUpload"
              :on-success="(response,file)=>{return handleFileSuccess(response ,file ,scope.row,scope.$index)}"                  
            >
              <el-button size="medium" type="text">{{scope.row.fileName?scope.row.fileName:'上传'}}</el-button>
            </el-upload>
          </template>
        </el-table-column>
        <!-- <el-table-column label="系统名称" align="center" prop="appName" :show-overflow-tooltip="true" width="120"></el-table-column>
        <el-table-column label="系统创建时间" align="center" prop="createdTime" width="120"></el-table-column>
        <el-table-column label="系统创建人" align="center" prop="appCreatedUser" width="120"></el-table-column>
        <el-table-column label="系统更新时间" align="center" prop="updatedTime" width="120"></el-table-column>
        <el-table-column label="系统更新人" align="center" prop="appUpdatedUser" :show-overflow-tooltip="true" width="120"></el-table-column>
        <el-table-column label="系统联系人" align="center" prop="relationUser" width="120"></el-table-column>
        <el-table-column label="系统联系人电话" align="center" prop="relationUserPhone" width="120"></el-table-column>
        <el-table-column label="系统联系人邮箱" align="center" prop="relationUserEmail" width="120"></el-table-column>
        <el-table-column label="系统备注" align="center" prop="appNote" :show-overflow-tooltip="true" width="120"></el-table-column>
        <el-table-column label="系统域名" align="center" prop="appDomain" width="120"></el-table-column>
        <el-table-column label="系统内网地址" align="center" prop="appInUrl" width="120"></el-table-column>
        <el-table-column label="系统外网地址" align="center" prop="appOutUrl" width="120"></el-table-column>
        <el-table-column label="服务商名称" align="center" prop="serviceProviderName" width="120"></el-table-column> -->
        
        <!-- <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleView(scope.row)"
              >查看详情</el-button
            >
          </template>
        </el-table-column> -->
      </el-table>
      <el-pagination
        v-show="total > 0"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-size="queryForm.pageSize"
        :current-page="queryForm.pageNum"
        :page-sizes="[10, 20, 30, 50, 100]"
      >
      </el-pagination>
    </el-card>
    <el-dialog
      title="数据概览"
      :visible.sync="showDialog"
      width="70%"
      :before-close="handleClose"
      custom-class="dialog-box"
      top="12"
    >
      <el-table v-loading="loading" :data="selectTableData" border>
        <el-table-column label="序号" align="center" width="65" type="index" />
        <el-table-column
          v-for="item in columnData" 
          :key="item.key"
          :label="item.label"
          align="center"
          :prop="item.prop"
          :show-overflow-tooltip="true"
        />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submitForm">导 出</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  listProjectDetailsExport,
  exportProjectDetailsExport,
  projectInfoUpload,
} from "@/api/manage/projectDetailsExport";
import {getApplyCompany,} from "@/api/manage/manage";
import { getToken } from "@/utils/auth"; 

export default {
  name: "Organization",
  data() {
    return {
      // 遮罩层
      loading: true,
      showDialog: false, //弹框显示
      // 总条数
      total: 0,
      // 机构管理表格数据
      projectDetailsExportList: [],
      // 日期范围
      dateRange: [],
      // 项目单位字典查询
      proCompanyOptions:[],
      // 查询参数
      queryForm: {
        pageNum: 1,
        pageSize: 10,
        ids: [],
        proCompany: "",
        proEndInvestmentEstimation: "",
        proName: "",
        proNature: "",
        proStag: "",
        proStartInvestmentEstimation: "",
        proType: "",
      },
      // 选择数据总条数
      lengthTotal: 0,
      // 弹窗表格数据
      selectTableData: [],
      // 表格列数据对应字段
      columnData:[
        {label:'项目名称',prop:'proName',key:0},
        {label:'项目性质',prop:'proNature',key:1},
        {label:'项目类别',prop:'proType',key:2},
        {label:'项目投资估算(万元)',prop:'proInvestmentEstimation',key:3},
        {label:'项目阶段',prop:'proStag',key:4},
        {label:'项目节点',prop:'proNode',key:5},
        {label:'项目申报时间',prop:'proTime',key:6},
        {label:'项目建设单位',prop:'proCompany',key:7},
        {label:'项目所属部门',prop:'proDept',key:8},
        {label:'项目联系人',prop:'proRelationUser',key:9},
        {label:'项目联系人电话',prop:'proRelationUserPhone',key:10},
        {label:'资料库',prop:'fileName',key:11},
      ],
      // 上传文件参数 当前行
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/file/upload",
      },
    };
  },
  created() {
    this.getList();
    // this.getDicts("sys_normal_disable").then((response) => {
    //   this.statusOptions = response.data;
    // });
    getApplyCompany().then((res) => {
        if (res.code == 200) {
          this.proCompanyOptions = res.companyList;
        }
      });
  },
  methods: {
    /** 日期处理 */
    changeDate(val) {
      if (val) {
        this.queryForm.starTime = val[0] + " 00:00:00";
        this.queryForm.endTime = val[1] + " 23:59:59";
      }
    },
    /** 查询项目明细列表 */
    getList() {
      this.loading = true;
      listProjectDetailsExport(this.queryForm).then(
        (response) => {
          if(response.code==200){
            this.projectDetailsExportList = [];
            let temporaryData = response.rows
            // 合并数据项目信息和系统信息
            temporaryData.map(item=>{
              item.temporaryRow = Object.assign(item.projectInfo, item.projectSystemInfo, item.file);
              this.projectDetailsExportList.push({
                fileName: '',
                fileUrl: '',
                ...item.temporaryRow,
              })
            })
            console.log(111,temporaryData,this.projectDetailsExportList);
            // 投资估算处理
            const regexp=/(?:\.0*|(\.\d+?)0+)$/
            this.projectDetailsExportList.map(item=>{
             item.proInvestmentEstimation = item.proInvestmentEstimation.replace(regexp,'$1')
            })
            this.total = response.total;
            this.loading = false;
          }
        }
      );
    },
    /** 选中的数据 */
    handleSelectionChange(val) {
      this.lengthTotal = val.length;
      this.multipleSelection = val;
      this.selectTableData = val;
    },
    /** 导出按钮操作 */
    exportClick() {
      console.log(999, this.selectTableData, this.selectTableData.length);
      if (this.selectTableData && this.selectTableData.length > 0) {
        this.showDialog = true;
      } else {
        this.$message.error("请先选择数据后导出");
      }
    },
    /** 关闭按钮操作 */
    handleClose() {
      this.showDialog = false;
    },
    /** 导出勾选确认 */
    submitForm() {
      let ids = []
      this.selectTableData.forEach(item=>ids.push(item.proId))
      return exportProjectDetailsExport({
        ids: ids,
      }).then(() => {
        this.showDialog = false;
      });
    },
    /** 导出全部 */
    handleExport() {
      this.$confirm(`是否导出全部,共${this.total}条数据?`, "导出", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "info",
      }).then(() => {
        return exportProjectDetailsExport(this.queryForm);
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryForm.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryForm.proStartInvestmentEstimation = undefined;
      this.queryForm.proEndInvestmentEstimation = undefined;
      this.queryForm.proNature = undefined;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 查看按钮操作*/
    handleView(row) {
      this.$router.push({
        path: "/business_manage/manage/expertsdraw/detailsNoEvaluate",
        query: {
          type: 1,
          id: row.reviewTaskId,
          way: 4,
        },
      });
    },
    /** 分页 */
    handleSizeChange(val) {
      this.queryForm.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.queryForm.pageNum = val;
      this.getList();
    },
    // 文件上传中处理 （当前行资料库）
    handleFileUpload(event, file, fileList) {
      console.log("文件上传中", file);
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, row,index) {
      console.log("文件上传成功", response, file ,row,index);
      this.$refs[`uploadFileRow${index}`].clearFiles();
      if(response.code!=500&&response.data){
        const data={
          fileName:file.name,
          fileUrl:response.data.fileUrl,
        }
        this.$forceUpdate(); //强制刷新，解决页面不会重新渲染的问题
        projectInfoUpload(row.proId,data).then(res=>{
          if(res.code === 200){
            row.fileName = file.name;
            row.fileUrl = response.data.fileUrl;
          }
        })
      }else{
        this.$message.error(response.msg)
      }
    },
    // 删除当前行文件操作
    handDelFile(row){
      const data = {
        fileName:'',
        fileUrl:'',
      }
      projectInfoUpload(row.proId,data).then(res=>{
          if(res.code === 200){
            row.fileName = '';
            row.fileUrl = '';
          }
        })
    },
    //下载当前行文件操作
    handDownload(file){
      if (file) {
        window.location.href = file;
      }
    }
  },
};
</script>
<style scoped lang="scss">
.organization-title {
  font-size: 18px;
  font-family: PingFang SC, PingFang SC-Medium;
  font-weight: 500;
  margin-bottom: 24px;
  color: #000000;
}
.card-table {
  margin-top: 10px;
  .el-pagination {
    text-align: center;
    margin-top: 40px;
  }
}
</style>
<style lang="scss">
/**表单label取消加粗 */
.card-form {
  .el-card__body {
    padding-bottom: 0;
  }
  label {
    font-weight: normal !important;
  }
  .el-form--inline .el-form-item {
    margin-right: 60px;
  }
}
/* 弹出窗样式 */
.dialog-box {
  .el-dialog__body {
    padding: 24px 69px 24px 69px;
    border-top: 1px solid #ebecef;
    border-bottom: 1px solid #ebecef;
    label {
      font-weight: 400 !important;
    }
  }
  .el-dialog__footer {
    padding: 16px 20px;
  }
  .el-dialog__headerbtn {
    background: url("../../../assets/images/icon_dialog_close.png");
    background-size: 100%;
    width: 16px;
    height: 16px;
    .el-dialog__close {
      visibility: hidden;
    }
  }
}
/* el-descriptions-item 文字居中 */
.el-descriptions__body .el-descriptions__table .el-descriptions-item__cell {
  text-align: center;
}
/* 删除弹出框样式 */
.del_box {
  width: 345px;
  height: 175px;
  .el-message-box__headerbtn {
    background: url("../../../assets/images/icon_dialog_close.png");
    background-size: 100%;
    width: 16px;
    height: 16px;
    .el-message-box__close {
      visibility: hidden;
    }
  }
  .el-message-box__content {
    padding: 26px 95px;
    font-size: 16px;
    .el-message-box__status.el-icon-warning {
      color: #ea4747;
    }
    .el-message-box__status + .el-message-box__message {
      padding-right: 0;
    }
  }
}
/** 当前行btn按钮宽度限制 */ 
.el-table .fixed-width .file-btn-width{
  width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  -webkit-line-clamp: 1;
}
</style>
